package com.tanhua.admin.listeners;

import com.tanhua.autoconfig.templates.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class AuditListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate template;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.audit.queue"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "audit.movement"
            )
    )
    public void audit(String movementId) throws Exception {
        System.out.println("需要审核的动态id="+movementId);
        //1、根据动态id，查询动态
        Movement movement = movementApi.findById(movementId);
        if(movement !=null && movement.getState() == 0) { //判断：防止消息的重复消费
            //2、获取动态中的文本内容和图片内容
            String text = movement.getTextContent();
            List<String> medias = movement.getMedias();
            //3、调用阿里云内容审核，审核文本，审核图片
            Map<String, String> textScan = template.greenTextScan(text);
            String textSugg = textScan.get("suggestion");
            Map<String, String> imageScan = template.imageScan(medias);
            String imageSugg = imageScan.get("suggestion");
            //4、统计文本和图片的审核结果，如果全部通过设置状态为1
            Integer state = 2;
            if(textSugg.equals("pass") && imageSugg.equals("pass")) {
                state =1;
            }
            movementApi.updateState(movementId,state);
        }

    }
}
